<template>
  <basic-container>
    <div class="receiving-container">
      <el-row>
        <!--左侧表单-->
        <el-col :span="8">
          <div class="avue-group__header avue-group">
            <i class="el-icon-vertical-bar avue-group__icon"></i>
            <h1 class="avue-group__title">单据信息</h1>
          </div>
          <el-tabs v-model="receivingType" @tab-click="handleClick">
            <el-tab-pane label="手动收料" name="handMovement"></el-tab-pane>
            <el-tab-pane label="批量收料" name="batch"></el-tab-pane>
          </el-tabs>
          <avue-form ref="properties" v-model="properties" :option="propertiesOption" @submit="handleMovementSubmit" v-if="receivingType === 'handMovement'">
            <template #receiveQuantity="{}"
              ><el-input v-model="properties.receiveQuantity" placeholder="请输入 本次收货数量" oninput="value= value.replace(/^\D*(\d*(?:\.\d{0,5})?).*$/g, '$1')"></el-input
            ></template>
            <!--            <template slot-scope="{ size }" slot="menuForm">-->
            <!--              <el-button type="success" size="small" icon="el-icon-upload2" @click="handleImportData">导入</el-button>-->
            <!--            </template>-->
          </avue-form>
          <div class="batch" v-if="receivingType === 'batch'">
            <el-button type="primary" size="small" icon="el-icon-check" @click="handleBatchSubmit" v-preventReClick>收料</el-button>
            <el-button type="success" size="small" icon="el-icon-upload2" @click="handleImportData">导入</el-button>
          </div>
        </el-col>
        <!--右侧表格-->
        <el-col :span="16">
          <div class="avue-group__header avue-group">
            <i class="el-icon-vertical-bar avue-group__icon"></i>
            <h1 class="avue-group__title">物料数据</h1>
          </div>
          <avue-crud
            :option="option"
            :table-loading="loading"
            :data="data"
            :page.sync="page"
            :permission="permissionList"
            @search-change="searchChange"
            @search-reset="searchReset"
            @row-del="rowDel"
            @row-update="addUpdate"
            @row-save="rowSave"
          >
            <template slot-scope="{ row }" slot="receiveQuantityForm"
              ><el-input v-model="row.receiveQuantity" placeholder="请输入 本次收货数量" oninput="value= value.replace(/^\D*(\d*(?:\.\d{0,5})?).*$/g, '$1')"></el-input
            ></template>
          </avue-crud>
        </el-col>
      </el-row>
    </div>
    <!-- 通用模态框-->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    <!--导入组件-->
    <front-end-import
      :title="importConfig.title"
      :url="importConfig.url"
      :mapfields="mapFields"
      :export-name="importConfig.exportName"
      :export-code="importConfig.exportCode"
      :visible.sync="importConfig.show"
      @save="handleLoadData"
    ></front-end-import>
  </basic-container>
</template>

<script>
import frontEndImport from '@/components/frontEndImport/frontEndImport';
import commonModalTemplate from '@/components/common-modal-template/common-modal-template';
import { refactorRemove, refactorSubmitReceive, refatorGetList, submitBatchReceive, submitReceive } from '@/api/warehouse/receiving';
import { mapGetters } from 'vuex';
import { getList as getAttributeConfigList } from '@/api/system/custom-attribute-config';
export default {
  components: {
    frontEndImport,
    commonModalTemplate
  },
  name: 'otherReceiveMaterial',
  mixins: [],
  data() {
    return {
      importConfig: {
        // todo
        show: false,
        exportName: '其他收料批量导入.xlsx',
        title: '其他收料导入',
        exportCode: '',
        url: ''
      },
      mapFields: {
        供应商名称: 'vendorName',
        '*供应商编码': 'vendorCode',
        送货单号: 'supplierOrderNumber',
        '*物料编码': 'partNo',
        物料名称: 'partName',
        '*本次收货数量': 'receiveQuantity',
        'D/C': 'dateCode',
        生产日期: 'vendorDate',
        检验批次: 'inspectionLotNo',
        供应商批次: 'vendorLotNo',
        '供应商类型(只能填客户或者供应商)': 'partnerName',
        备注: 'description'
      },
      receivingType: 'handMovement',
      timer: new Date().getTime(),
      properties: {},
      tableOption: {},
      propertiesOption: {
        submitText: '收料',
        labelWidth: 130,
        menuSpan: 20,
        column: [
          {
            label: '供应商名称',
            prop: 'vendorName',
            type: 'search',
            display: true,
            disabled: true,
            row: true,
            span: 20,
            rules: [
              {
                required: true,
                message: '请选择供应商名称',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openVendorModal();
            }
          },
          {
            label: '物料名称',
            prop: 'partName',
            type: 'search',
            disabled: true,
            span: 20,
            row: true,
            rules: [
              {
                required: true,
                message: '请选择物料名称',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openPartModal();
            }
          },
          {
            label: '物料编码',
            prop: 'partNo',
            disabled: true,
            span: 20,
            row: true
          },
          {
            label: '送货单',
            prop: 'supplierOrderNumber',
            span: 20,
            row: true
          },
          {
            label: '本次收货数量',
            prop: 'receiveQuantity',
            type: 'number',
            precision: 5,
            span: 20,
            controls: false,
            row: true,
            rules: [
              {
                required: true,
                message: '请输入收货数量',
                trigger: 'blur'
              },
              {
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  if (!value || value <= 0) {
                    callback(new Error('收货数量需大于0'));
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '备注',
            prop: 'description',
            type: 'textarea',
            row: true,
            span: 20,
            maxRows: 3,
            minRows: 3
          }
        ]
      },
      data: [],
      localData: [], // 存储数据 用于搜索
      query: {},
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      loading: false,
      option: {
        height: 'calc(100vh - 485px)',
        calcHeight: 30,
        rowKey: 'partNo',
        tip: false,
        searchMenuSpan: 4,
        searchMenuPosition: 'right',
        cellBtn: true,
        border: true,
        index: true,
        indexLabel: '行号',
        selection: false,
        dialogClickModal: false,
        searchLabelWidth: 100,
        searchSpan: 6,
        addBtn: false,
        editBtn: true,
        viewBtn: false,
        refreshBtn: false,
        searchShowBtn: false,
        delBtn: true,
        menuWidth: 200,
        menu: false,
        columnBtn: false,
        column: [
          {
            label: '供应商名称',
            prop: 'vendorName',
            cell: true
          },
          {
            label: '供应商编码',
            prop: 'vendorCode',
            cell: true
          },
          {
            label: '送货单',
            prop: 'supplierOrderNumber',
            cell: true
          },
          {
            label: '物料编码',
            prop: 'partNo',
            width: 150,
            cell: true,
            search: true,
            searchOrder: 4
          },
          {
            label: '物料名称',
            prop: 'partName',
            cell: true,
            search: true,
            searchOrder: 5
          },
          {
            label: '本次收货数量',
            prop: 'receiveQuantity',
            width: 200,
            type: 'number',
            precision: 5,
            min: 0,
            cell: true
          },
          {
            label: '备注',
            prop: 'description',
            cell: true
          }
        ]
      },
      customAttributeList: [] //扩展属性
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        delBtn: this.vaildData(this.permission.warehousing_records_view, false)
      };
    }
  },
  // created() {
  //   let path = this.$route.path;
  //   // getAttributeConfigList(path).then((res) => {
  //   //   this.customAttributeList = this._get(res, 'data.data', []);
  //   //   this._forEach(this.customAttributeList, (item) => {
  //   //     this.propertiesOption.column.push({
  //   //       label: item.lableCnName,
  //   //       prop: item.attributeKey,
  //   //       type: item.controlType,
  //   //       value: item.defaultValue,
  //   //       dispaly: item.enabled,
  //   //       span: 20
  //   //     });
  //   //   });
  //   // });
  // },
  methods: {
    searchChange(params, done) {
      this.data = this.localData.filter((item) => {
        for (let key in params) {
          if (!item[key].includes(params[key])) {
            return false;
          }
        }
        return true;
      });
      done();
    },
    searchReset() {
      this.query = {};
      this.data = this.localData;
    },
    async handleMovementSubmit(form, done) {
      this.properties.vendorDate = this.properties.vendorDate ? this.$moment(this.properties.vendorDate).format('yyyy-MM-DD HH:mm:ss') : '';
      const tempData = this._cloneDeep(this.properties);
      if (this.receivingType === 'handMovement') {
        this.$refs.properties.validate(async (valid, done) => {
          if (valid) {
            this.properties['receiveType'] = 'OTHER';
            this.properties['partMasterId'] = this.properties.partId;
            if (this.customAttributeList.length > 0) {
              let extFields = {};
              this._forEach(this.customAttributeList, (item) => {
                for (let key in this.properties) {
                  if (item.attributeKey === key) {
                    extFields[key] = this.properties[key];
                  }
                }
              });
              this.properties['extFields'] = JSON.stringify(extFields);
            }
            let params = {
              packingList: [],
              receivingList: [this.properties]
            };
            try {
              await submitReceive(params);
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.data.push(tempData);
              this.localData.push(tempData);
              this.$refs.properties.resetForm();
            } catch (e) {
              console.warn(e);
            }
            done();
          }
        });
      }
      done();
    },
    async handleBatchSubmit() {
      const valid = this.data.every((item, index) => {
        item.partnerType = item.partnerName === '供应商' ? 'SUPPLIER' : 'CUSTOMER';
        const receiveQuantity = Number(item.receiveQuantity);
        if (receiveQuantity && receiveQuantity >= 0) {
          return true;
        } else {
          this.$message.error(`数据第${index + 1}行收货数量不正确, 请输入正确的收货数量`);
          return false;
        }
      });
      if (!valid) {
        return;
      }
      let params = {
        packingList: [],
        receivingList: [...this.data],
        receiveType: 'OTHER'
      };
      try {
        await submitBatchReceive(params);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        if (this.receivingType === 'batch') {
          this.data = [];
        }
      } catch (e) {
        console.warn(e);
      }
    },
    handleLoadData(data) {
      this.localData = data;
      this.data = data;
    },
    rowDel(row, index) {
      this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.data.splice(index, 1);
      });
    },
    addUpdate(form, index, done, loading) {
      done();
    },
    rowSave(form, done) {
      done();
    },
    handleImportData() {
      this.importConfig.show = true;
    },
    getSelectedRows(rowData, title) {
      console.log(rowData, title);
      if (title === 'partInfo') {
        this.properties['partName'] = rowData.name;
        this.properties['partNo'] = rowData.partNo;
        this.properties['partId'] = rowData.id;
      } else {
        this.properties['vendorName'] = rowData.name;
        this.properties['vendorCode'] = rowData.partnerNo;
        this.properties['partnerType'] = rowData.partnerType;
        this.properties['partnerName'] = rowData.partnerType === 'CUSTOMER' ? '客户' : '供应商';
      }
    },
    handleClick(tab, event) {
      if (this.receivingType === 'handMovement') {
        this.$set(this.option, 'menu', false);
      } else if (this.receivingType === 'batch') {
        this.$set(this.option, 'menu', true);
      }
      this.data = [];
      this.localData = [];
    },
    /**
     * 供应商模态框
     */
    openVendorModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择供应商信息（双击进行选择）',
        url: '/api/mes-admin/partner/page?multiPartnerType=SUPPLIER,CUSTOMER',
        isPage: true,
        selection: true,
        rowSelectionType: 'single',
        titleInfo: 'vendorInfo',
        columnDefs: [
          {
            label: '类型',
            prop: 'partnerType',
            type: 'select',
            // dicUrl: '/api/blade-system/dict/dictionary?code=partner_type',
            // props: {
            //   label: 'dictValue',
            //   value: 'dictKey'
            // },
            formatter: (val) => {
              if (val.partnerType == 'SUPPLIER') {
                return '供应商';
              } else {
                return '客户';
              }
            },
            rules: [
              {
                required: true,
                message: '请输入类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '编码',
            prop: 'code',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '缩写',
            prop: 'abbreviation',
            rules: [
              {
                required: true,
                message: '请输入缩写',
                trigger: 'blur'
              }
            ]
          }
        ]
      };
    },
    /**
     * 物料模态框
     */
    openPartModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择物料信息（双击进行选择）',
        url: '/api/mes-admin/part-master/page',
        isPage: true,
        selection: true,
        isDefaultLoad: true,
        rowSelectionType: 'single',
        titleInfo: 'partInfo',
        noResetRequest: true,
        searchMenuSpan: 24,
        columnDefs: [
          {
            label: '类型',
            prop: 'semifinished',
            search: true,
            hide: true,
            type: 'select',
            searchValue: 'false',
            dicData: [
              {
                label: '原材料',
                value: 'false'
              },
              {
                label: '在制品',
                value: 'true'
              }
            ],
            searchRules: [
              {
                required: true,
                message: '请选择类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '类别',
            prop: 'categoryId',
            search: true,
            type: 'tree',
            dicUrl: '/api/mes-admin/part-category/tree',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '型号',
            prop: 'partModel'
          },
          {
            label: '描述',
            prop: 'description'
          },
          {
            label: '版本',
            prop: 'revision'
          }
        ]
      };
    },
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style scoped lang="scss">
.receiving-container {
  height: 82vh;
  margin: 0 12px;
}
</style>
